package com.douyu.ocean.invoke;

import com.google.common.base.Stopwatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * @author leiruiqi on 2018/9/11
 */
@Aspect
@Component
public class PerformanceAspect {

    @Around("@annotation(performance)")
    public Object around(ProceedingJoinPoint pjp,PerformanceAnnotation performance) {
        //获取注解里的值
        String name = performance.name();
        if(name.equals("")){
            name = pjp.getSignature().getName();
        }
        double boost = performance.boost();
        boolean throwe = performance.throwe();
        boolean autoRefuse = performance.autoRefuse();
        String type = performance.type();
        String actionName = type+name;
        //System.out.println(actionName);
        if(autoRefuse){
            if(!PerformanceCore.needInvoke(PerformanceCore.getInvokeRateByName(actionName),boost)){
                return null;
            }
        }

        Stopwatch stopwatch = Stopwatch.createStarted();
        boolean excuteResult = true;
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            excuteResult = false;
            if(throwe){
                throw new RuntimeException(throwable);
            }else{
                return null;
            }
        } finally {
            //耗时收集
            stopwatch.stop();
            long micro = stopwatch.elapsed(MICROSECONDS);
            PerformanceCollectUtil.saveRecord(actionName,micro,excuteResult);
        }

    }
}
